import { View, ScrollView } from '@tarojs/components'
import { useEffect, useState } from 'react'
import { request } from "../../utils";
import { apis } from "../../constants";
import Taro from '@tarojs/taro';

import './index.scss'

interface newTypeList {
  typeId: number,
  typeName: string
}
interface newList {
  newsId: string,
  title: string,
  postTime: string,
  source: string


}
export default function News() {
  const [loading, setLoading] = useState(false);
  const [nav, setNav] = useState<Array<newTypeList>>([]);
  const [newsList, setNewsList] = useState<Array<newList>>([]);
  const [select, setSelect] = useState<number>();
  const [page, setPage] = useState<number>(1);

  //获取新闻类型
  const getNewsType = async () => {
    const data = await request({
      method: "GET",
      url: apis.newsType,
      data: {}
    });
    if (data.data) {
      setNav(data.data)
      setSelect(data.data[0].typeId)
    }

  }
  const getNewsList = async (typeId: number, page: number) => {
    const data = await request({
      method: "GET",
      url: apis.newsList,
      data: { typeId, page }
    });
    if (data.data) {
      setNewsList([...newsList, ...data.data])
    }
    setLoading(true)
    Taro.hideLoading();
  }

  //初
  useEffect(() => {
    setNewsList([])
    setPage(1)
  }, [select])

  useEffect(() => {
    if (!newsList.length && select) {
      getNewsList(select, 1)
    }
  }, [newsList])

  useEffect(() => {
    if (page > 1 && select) {
      getNewsList(select, page)
    }
  }, [page])


  useEffect(() => {
    Taro.showLoading({
      title: "加载中"
    });
    getNewsType()
  }, [])

  const changeType = (id: number) => {
    setSelect(id)
  }

  const scrollPage = () => {
    setPage(page + 1)
  }


  const toDetail = (id: string) => {
    Taro.navigateTo({
      url: `/pages/NewsDetail/index?newsId=${id}`
  });
  }

  return <View className='News'>
    {
      loading && <>
        <View className='news-l'>
          {
            nav.map(one => <View className={`news-nav ${select == one.typeId ? 'nav-active' : ''}`} key={one.typeId} onClick={() => changeType(one.typeId)}>
              {one.typeName}
            </View>)
          }
        </View>
        <ScrollView className='news-r' scrollY onScrollToLower={scrollPage}>
          {
            newsList.map(one => <View className='news-list' key={one.newsId} onClick={() => toDetail(one.newsId)}>
              <View className='news-title'>
                {one.title}
              </View>
              <View>来自：{one.source}</View>
              <View >时间：{one.postTime}</View>
            </View>)
          }
        </ScrollView>
      </>
    }
  </View>
}
